package com.ncepu.thumb.mq.rabbit.consumer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ncepu.thumb.mq.rabbit.constant.RabbitMQConstant;
import com.ncepu.thumb.model.entity.Blog;
import com.ncepu.thumb.model.entity.Thumb;
import com.ncepu.thumb.mq.msg.ThumbEvent;
import com.ncepu.thumb.service.BlogService;
import com.ncepu.thumb.service.ThumbService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.ZoneId;
import java.util.Date;

/**
 * @author simon_jiang
 * @version 1.0
 */
@Component
@Slf4j
public class ThumbEventConsumer {

    @Resource
    private ThumbService thumbService;
    @Resource
    private BlogService blogService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = {RabbitMQConstant.QUEUE})
    public void consume(ThumbEvent thumbEvent) {
        try {
            log.info("接收到消息: {}", thumbEvent);
            processMessage(thumbEvent);
        } catch (Exception e) {
            log.error("处理消息失败: {}", thumbEvent, e);
            // 进入死信队列
            rabbitTemplate.convertAndSend(RabbitMQConstant.DEAD_DIRECT_EXCHANGE, RabbitMQConstant.DEAD_ROUTING_KEY, thumbEvent);
        }
    }

    @Retryable(
            value = {Exception.class},  // 捕获的异常类型
            maxAttempts = 3,  // 最大重试次数
            backoff = @Backoff(delay = 1000, multiplier = 2)  // 重试间隔和倍数
    )
    private void processMessage(ThumbEvent thumbEvent) {
        Boolean isSuccessConsumed = false;
        // 根据事件类型处理逻辑
        if (thumbEvent.getType() == ThumbEvent.EventType.INCR) {
            // 点赞事件处理
            log.info("处理点赞事件，博客ID: {}", thumbEvent.getBlogId());
            // 调用相关服务逻辑
            isSuccessConsumed = transactionTemplate.execute(status -> {
                Thumb thumb = new Thumb();
                thumb.setUserId(thumbEvent.getUserId());
                thumb.setBlogId(thumbEvent.getBlogId());
                thumb.setCreateTime(Date.from(thumbEvent.getEventTime().atZone(ZoneId.systemDefault()).toInstant()));
                boolean save = thumbService.save(thumb);

                boolean update = blogService.lambdaUpdate()
                        .setSql("thumbCount = thumbCount + 1")
                        .eq(Blog::getId, thumbEvent.getBlogId())
                        .update();
                return save && update;
            });
        } else if (thumbEvent.getType() == ThumbEvent.EventType.DECR) {
            // 取消点赞事件处理
            log.info("处理取消点赞事件，博客ID: {}", thumbEvent.getBlogId());
            // 调用相关服务逻辑
            isSuccessConsumed = transactionTemplate.execute(status -> {
                LambdaQueryWrapper<Thumb> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Thumb::getBlogId, thumbEvent.getBlogId())
                        .eq(Thumb::getUserId, thumbEvent.getUserId());
                boolean remove = thumbService.remove(wrapper);

                boolean update = blogService.lambdaUpdate()
                        .setSql("thumbCount = thumbCount - 1")
                        .eq(Blog::getId, thumbEvent.getBlogId())
                        .update();
                return remove && update;
            });
        }
        if(!isSuccessConsumed) {
            throw new RuntimeException("处理消息失败");
        }
    }
}
